import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.FileReader;
import java.util.*;

public class Compiler {
    private static Object yamlData;

    public static void main(String[] args) {
        int cmdstart = 0;
        if(args.length < 1){
            System.out.println("Invalid input!");
            return;
        }
        if(args[0].equals("yamlite")) cmdstart++;
        //判断是否为合法命令结构
        if (args.length - cmdstart < 1 || args.length - cmdstart > 3 || (args.length - cmdstart == 3 && !args[cmdstart].equals("-find"))) {
            System.out.println("Invalid input!");
            return;
        }
        String fname;
        if (args.length - cmdstart == 1) {
            fname = args[cmdstart];
            System.out.println(matchParse(fname));
        } else if (args.length - cmdstart == 2) {
            fname = args[cmdstart + 1];
            if (args[cmdstart].equals("-parse")) {
                System.out.println(matchParse(fname));
            } else if (args[cmdstart].equals("-json")) {
                matchJson(fname);
            } else {
                System.out.println("Invalid option");
            }
        } else {
            fname = args[cmdstart + 2];
            matchFind(fname, args[cmdstart + 1]);
        }
    }

    //按标准格式输出报错位置与信息
    private static String throwExStr(int line, int pos, String message) {
        return "line " + line + ", position " + pos + ": " + message + ".";
    }

    //匹配正负整数、浮点数及科学计数法对应的数字合法值
    private static int matchNum(int pos, String str) {
        if (str.charAt(pos) == '-') pos++;
        while (pos < str.length() && str.charAt(pos) >= '0' && str.charAt(pos) <= '9') {
            pos++;
        }
        if (pos >= str.length()) {
            return pos;
        } else if (str.charAt(pos) == 'e' || str.charAt(pos) == 'E') {
            pos++;
            if (pos == str.length() || (str.charAt(pos) != '+' && str.charAt(pos) != '-')) {
                return pos - 1;
            }
            pos++;
            if (pos == str.length() || str.charAt(pos) < '0' || str.charAt(pos) > '9') {
                return pos - 1;
            }
            while (pos < str.length() && str.charAt(pos) >= '0' && str.charAt(pos) <= '9') {
                pos++;
            }
        } else if (str.charAt(pos) == '.') {
            pos++;
            if (pos == str.length() || (str.charAt(pos) < '0' && str.charAt(pos) > '9')) {
                return pos - 1;
            } else {
                pos++;
            }
            while (pos < str.length() && str.charAt(pos) >= '0' && str.charAt(pos) <= '9') {
                pos++;
            }
            if (pos < str.length() && (str.charAt(pos) == 'e' || str.charAt(pos) == 'E')) {
                pos++;
                if (str.charAt(pos) == '+' || str.charAt(pos) == '-') {
                    pos++;
                }
                if (pos == str.length() || (str.charAt(pos) < '0' && str.charAt(pos) > '9')) {
                    return pos - 1;
                }
                while (pos < str.length() && str.charAt(pos) >= '0' && str.charAt(pos) <= '9') {
                    pos++;
                }
            }
        }
        return pos;
    }

    //匹配布尔合法值
    private static int matchBoolean(int pos, String str) {
        if (pos + 4 <= str.length() && str.substring(pos, pos + 4).equals("true")) {
            return pos + 4;
        } else if (pos + 5 <= str.length() && str.substring(pos, pos + 5).equals("false")) {
            return pos + 5;
        } else {
            return pos;
        }
    }

    //匹配字符串合法值
    private static int matchString(int line, int pos, String str) {
        try {
            pos++;
            while (pos < str.length() - 1 && str.charAt(pos) != '"') {
                pos++;
            }
            if (str.charAt(pos) != '"') {
                throw new Exception(throwExStr(line, pos + 1, "expected <\">"));
            }
            pos++;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return -1;
        }
        return pos;
    }

    //匹配键值对的键名及之后的冒号
    private static int matchKey(int line, int pos, String str) {
        try {
            while (pos < str.length() && str.charAt(pos) != ':') {
                if (str.charAt(pos) < '0' || (str.charAt(pos) > '9' && str.charAt(pos) < 'A') ||
                        (str.charAt(pos) > 'Z' && str.charAt(pos) < '_') ||
                        (str.charAt(pos) > '_' && str.charAt(pos) < 'a') ||
                        str.charAt(pos) > 'z') {
                    throw new Exception(throwExStr(line, pos, "Invalid key"));
                }
                pos++;
            }
            if (str.charAt(pos - 1) == '_') {
                throw new Exception(throwExStr(line, pos, "Invalid key"));
            }
            if (pos < str.length() && str.charAt(pos) == ':') {
                pos++;
            } else {
                throw new Exception(throwExStr(line, pos, "expected <:>"));
            }
            if (pos < str.length() && str.charAt(pos) == ' ') {
                pos++;
            } else if (pos == str.length()) {
                return pos;
            } else {
                throw new Exception(throwExStr(line, pos, "expected < >"));
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return -1;
        }
        return pos;
    }

    //匹配键值对对应的合法值
    private static int matchValue(int line, int pos, String str) {
        try {
            if (pos == str.length()) {
                throw new Exception(throwExStr(line, pos, "expected value"));
            } else if ((str.charAt(pos) >= '0' && str.charAt(pos) <= '9') || str.charAt(pos) == '-') {
                pos = matchNum(pos, str);
            } else if (str.charAt(pos) == 't' || str.charAt(pos) == 'f') {
                pos = matchBoolean(pos, str);
            } else if (str.charAt(pos) == '"') {
                pos++;
                pos = matchString(line, pos, str);
            } else {
                throw new Exception(throwExStr(line, pos, "Invalid value"));
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return -1;
        }
        return pos;
    }

    //匹配数组内元素对应的合法值
    private static int matchArrayValue(int line, int pos, String str) {
        try {
            if (str.charAt(pos) != ' ') {
                throw new Exception(throwExStr(line, pos, "expected < >"));
            }
            pos++;
            pos = matchValue(line, pos, str);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return -1;
        }
        return pos;
    }

    //parse选项下的文件解析、读取与存储操作
    //同时根据传入布尔值判断是否需要打印解析成功后的信息
    private static String matchParse(String fname) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(fname));
            String fline, keyName = "", keyValue = "";
            int line = 0, pos, level = 0, fstart = 0, fend = 0;
            boolean newIndent = false, isKey = true, getType = false;
            ArrayList<Object> cur = new ArrayList<Object>();
            ArrayList<ArrayList<Object>> all = new ArrayList<ArrayList<Object>>();
            LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
            HashMap<String, Object> tmap = map;
            ArrayList<Integer> keyLv = new ArrayList<Integer>();
            while ((fline = br.readLine()) != null) {
                line++;
                pos = 0;
                if (fline.length() == 0) continue;
                //删去第一个#符号之后的所有注释内容
                if (fline.contains("#")) {
                    if (fline.charAt(0) == '#') continue;
                    fline = fline.substring(0, fline.indexOf("#"));
                }
                //删除当前行尾部的所有空白字符
                int end = fline.length() - 1;
                while (end >= 0 && fline.charAt(end) == ' ') {
                    end--;
                }
                if (end < 0) continue;
                fline = fline.substring(0, end + 1);
                //获取当前行的缩进值
                int indent = 0;
                while (indent < fline.length() && fline.charAt(indent) == ' ') {
                    indent++;
                }
                if (indent == fline.length()) {
                    continue;
                }
                //判断Yaml文件第一层是数组还是键值对集合，并确定存储的数据类型
                if(!getType){
                    if(fline.charAt(0) == '-'){
                        yamlData = cur;
                        all.add(cur);
                        isKey = false;
                    }else if(matchKey(line, pos, fline) > 0){
                        yamlData = map;
                    }else {
                        return "Invalid data type";
                    }
                    getType = true;
                }
                pos = indent;
                if (keyLv.size() > 0 && indent / 2 > keyLv.get(keyLv.size() - 1)) {
                    for (int i = 0; i < keyLv.size(); i++) {
                        indent -= 2;
                    }
                }
                //根据缩进检测是否为第一层
                if (indent > 0) {
                    if (indent == level * 2 || (indent < level * 2 && indent % 2 == 0)) {
                        //若缩进减少，则删去keyLv记录中高于当前层的key层级，删去嵌套数组列表中保存的高于当前层的数组，并将层级定位到当前层
                        while (level * 2 > indent) {
                            level--;
                            if (keyLv.size() > 0 && level <= keyLv.get(keyLv.size() - 1)) {
                                keyLv.remove(keyLv.size() - 1);
                            }
                            all.remove(all.size() - 1);
                            cur = all.get(all.size() - 1);
                        }
                        //读取当前层-符号之后的合法值
                        //若只有-符号，则进入下一行读取新的子数组或是键值对
                        //否则，继续解析、读取并存储当前数组的合法值
                        if (fline.charAt(pos) == '-') {
                            if (pos == fline.length() - 1) {
                                newIndent = true;
                                continue;
                            } else {
                                pos++;
                                fstart = pos + 1;
                                pos = matchArrayValue(line, pos, fline);
                                if (pos == -1) throw new Exception("");
                                fend = pos;
                                keyValue = fline.substring(fstart, fend);
                                cur.add(keyValue);
                            }
                        } else {
                            throw new Exception(throwExStr(line, pos, "Invalid indent"));
                        }
                    } else if (newIndent && indent == level * 2 + 2) {
                        //若缩进增加，则先识别是否为数组内的键值对或是新的嵌套数组
                        //若为新的子数组，则先判断上一层是否为键值对或是数组，再存入嵌套数组列表
                        //若为新的键值对，则进行键值对的键、值解析、读取与存储操作
                        //新的键值对值为数组时，存储操作会在子数组的解析过程中进行
                        newIndent = false;
                        if (fline.charAt(pos) == '-') {
                            level++;
                            ArrayList<Object> tem = new ArrayList<Object>();
                            if (isKey) {
                                tmap.put(keyName, tem);
                                isKey = false;
                            } else {
                                cur.add(tem);
                            }
                            all.add(tem);
                            cur = tem;
                            if (pos == fline.length() - 1) {
                                newIndent = true;
                                continue;
                            } else {
                                pos++;
                                fstart = pos + 1;
                                pos = matchArrayValue(line, pos, fline);
                                if (pos == -1) throw new Exception("");
                                fend = pos;
                                keyValue = fline.substring(fstart, fend);
                                cur.add(keyValue);
                            }
                        } else {
                            fstart = pos;
                            pos = matchKey(line, pos, fline);
                            if (pos == -1) throw new Exception("");
                            fend = pos;
                            if (pos == fline.length() && fline.charAt(pos - 1) == ':') {
                                keyLv.add(level);
                                keyName = fline.substring(fstart, fend - 1);
                                tmap = new HashMap<String, Object>();
                                cur.add(tmap);
                                isKey = true;
                                newIndent = true;
                                continue;
                            } else {
                                keyName = fline.substring(fstart, fend - 2);
                                fstart = pos;
                                pos = matchValue(line, pos, fline);
                                if (pos == -1) throw new Exception("");
                                fend = pos;
                                keyValue = fline.substring(fstart, fend);
                                tmap = new HashMap<String, Object>();
                                tmap.put(keyName, keyValue);
                                cur.add(tmap);
                            }
                        }
                    } else {
                        throw new Exception(throwExStr(line, pos, "Invalid indent"));
                    }
                } else {
                    //若为无缩进的第一层，则先判断第一层为数组还是键值对集合，再进行解析、判断
                    if (yamlData instanceof ArrayList) {
                        if(fline.charAt(0) != '-'){
                            return "Invalid data type";
                        }
                        while (level * 2 > 0) {
                            level--;
                            if (keyLv.size() > 0 && level <= keyLv.get(keyLv.size() - 1)) {
                                keyLv.remove(keyLv.size() - 1);
                            }
                            all.remove(all.size() - 1);
                            cur = all.get(all.size() - 1);
                        }
                        if (pos == fline.length() - 1) {
                            newIndent = true;
                            continue;
                        } else {
                            pos++;
                            fstart = pos + 1;
                            pos = matchArrayValue(line, pos, fline);
                            if (pos == -1) throw new Exception("");
                            fend = pos;
                            keyValue = fline.substring(fstart, fend);
                            cur.add(keyValue);
                        }
                    }else if(yamlData instanceof LinkedHashMap){
                        fstart = pos;
                        pos = matchKey(line, pos, fline);
                        if (pos == -1) throw new Exception("");
                        fend = pos;
                        if (pos == fline.length() && fline.charAt(pos - 1) == ':') {
                            keyName = fline.substring(fstart, fend - 1);
                            newIndent = true;
                            continue;
                        } else {
                            keyName = fline.substring(fstart, fend - 2);
                            fstart = pos;
                            pos = matchValue(line, pos, fline);
                            if (pos == -1) throw new Exception("");
                            fend = pos;
                            keyValue = fline.substring(fstart, fend);
                            map.put(keyName, keyValue);
                        }
                    }
                }
                if(pos < fline.length()) throw new Exception(throwExStr(line, pos, "Invalid value"));
            }
            br.close();
            return "valid";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    //json选项下的json文件转化操作
    //通过调用parse操作函数并对存储的数据结构进行转化实现
    private static void matchJson(String fname) {
        String res = matchParse(fname);
        if(res.equals("valid")){
            String fpName = "", jName = "";
            for (int i = 0; i < fname.length(); i++) {
                if (fname.charAt(i) == '.') {
                    fpName = fname.substring(0, i);
                }
            }
            jName = fpName + ".json";
            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter(jName));
                if (yamlData instanceof ArrayList){
                    bw.write(arrayToJson((ArrayList<Object>) yamlData));
                }else if (yamlData instanceof LinkedHashMap){
                    bw.write(mapToJson((LinkedHashMap<String, Object>) yamlData));
                }
                bw.close();
                System.out.println(jName);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }else {
            System.out.println(res);
        }
    }

    //将键值对结构转化为json格式的字符串
    private static String mapToJson(HashMap<String, Object> tmap) {
        String str = "{";
        int i = 0;
        for (String key : tmap.keySet()) {
            if (i > 0) str += ", ";
            str += "\"" + key + "\": ";
            if (tmap.get(key) instanceof ArrayList) {
                str += arrayToJson((ArrayList<Object>) tmap.get(key));
            } else if (tmap.get(key) instanceof HashMap) {
                str += mapToJson((HashMap<String, Object>) tmap.get(key));
            } else {
                str += tmap.get(key).toString();
            }
            i++;
        }
        str += "}";
        return str;
    }

    //将数组结构转化为json格式的字符串
    private static String arrayToJson(ArrayList<Object> arr) {
        String str = "[";
        int i = 0;
        for (Object obj : arr) {
            if (i > 0) str += ", ";
            if (obj instanceof ArrayList) {
                str += arrayToJson((ArrayList<Object>) obj);
            } else if (obj instanceof HashMap) {
                str += mapToJson((HashMap<String, Object>) obj);
            } else {
                str += obj.toString();
            }
            i++;
        }
        str += "]";
        return str;
    }

    //find选项下的查询操作
    //通过调用parse操作函数并对存储的数据结构进行遍历搜索实现
    private static void matchFind(String fname, String path) {
        String res = matchParse(fname);
        if(res.equals("valid")){
            String result = "null";
            if (path.length() <= 0) result = "Invalid path!";
            if(yamlData instanceof LinkedHashMap){
                result = findInMap((LinkedHashMap<String, Object>)yamlData, 0, 0, path);
            }else if(yamlData instanceof ArrayList){
                result = findInArray((ArrayList<Object>)yamlData, 0, 0, path);
            }
            System.out.println(result);
        }else {
            System.out.println(res);
        }
    }

    //在键值对结构内对指定路径进行搜索
    private static String findInMap(HashMap<String, Object> tmap, int kstart, int kend, String path) {
        String keyName = "";
        while (kend < path.length() && path.charAt(kend) != '[') {
            kend++;
        }
        keyName = path.substring(kstart, kend);
        kstart = kend;
        for (String key : tmap.keySet()) {
            if (key.equals(keyName) && kend == path.length()) {
                if (tmap.get(key) instanceof ArrayList) {
                    return arrayToJson((ArrayList<Object>) tmap.get(key));
                } else if (tmap.get(key) instanceof HashMap) {
                    return mapToJson((HashMap<String, Object>) tmap.get(key));
                } else {
                    return tmap.get(key).toString();
                }
            } else if (key.equals(keyName) && path.charAt(kend) == '[' && tmap.get(key) instanceof ArrayList) {
                return findInArray((ArrayList<Object>) tmap.get(key), kstart, kend, path);
            }
        }
        return "null";

    }

    //在数组结构内对指定路径进行搜索
    private static String findInArray(ArrayList<Object> arr, int kstart, int kend, String path) {
        kend++;
        kstart = kend;
        int keyIdx;
        while (kend < path.length() && path.charAt(kend) != ']') {
            if (path.charAt(kend) >= '0' && path.charAt(kend) <= '9') {
                kend++;
            } else {
                return "null";
            }
        }
        if (kend == path.length() && path.charAt(kend - 1) != ']') {
            return "null";
        }
        String idxStr = path.substring(kstart, kend);
        keyIdx = Integer.parseInt(idxStr);
        keyIdx--;
        kend++;
        kstart = kend;
        if (keyIdx >= arr.size()) {
            return "null";
        } else if (kend == path.length()) {
            if (arr.get(keyIdx) instanceof ArrayList) {
                return arrayToJson((ArrayList<Object>) arr.get(keyIdx));
            } else if (arr.get(keyIdx) instanceof HashMap) {
                return mapToJson((HashMap<String, Object>) arr.get(keyIdx));
            } else {
                return arr.get(keyIdx).toString();
            }
        } else if (path.charAt(kend) == '[' && arr.get(keyIdx) instanceof ArrayList) {
            return findInArray((ArrayList<Object>) arr.get(keyIdx), kstart, kend, path);
        } else if (path.charAt(kend) == '.' && arr.get(keyIdx) instanceof HashMap) {
            kend++;
            kstart = kend;
            return findInMap((HashMap<String, Object>) arr.get(keyIdx), kstart, kend, path);
        } else {
            return "null";
        }
    }
}